package com.example.smartvillage.cunmin;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.smartvillage.MainViewModel;
import com.example.smartvillage.R;
import com.example.smartvillage.onenet.MyOneNetApi;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textview.MaterialTextView;
import com.google.gson.JsonArray;

import java.util.Objects;

public class BalconyFragment extends BottomSheetDialogFragment {

    private static final String TAG = "阳台控制";

    MainViewModel model;
    MyOneNetApi myOneNetApi;

    MaterialButton btn_up,btn_down,btn_light;
    MaterialTextView tv_state;

    public BalconyFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        model = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        myOneNetApi = Objects.requireNonNull(model.getMyOneNetApi().getValue());

        //每次进入更新数据
        boolean[] newBalconyStates = new boolean[2];
        String dataStreamId = "阳台上升,灯光4控制";
        myOneNetApi.getDataStreams(dataStreamId, response -> {
            if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                JsonArray obj = response.body().get("data").getAsJsonArray();
                newBalconyStates[0] = (obj.get(0).getAsJsonObject().get("current_value").getAsInt() == 1);
                newBalconyStates[1] = (obj.get(1).getAsJsonObject().get("current_value").getAsInt() == 1);
                Log.d(TAG, "获取的阳台状态，阳台：" + newBalconyStates[0] + "，照明：" + newBalconyStates[1]);
                model.setBalconyStates(newBalconyStates);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_balcony, container, false);

        btn_up = view.findViewById(R.id.balcony_up);
        btn_down = view.findViewById(R.id.balcony_down);
        btn_light = view.findViewById(R.id.balcony_light);
        tv_state = view.findViewById(R.id.balcony_state);

        btn_up.setOnClickListener(btnUpClickListener);
        btn_down.setOnClickListener(btnDownClickListener);
        btn_light.setOnClickListener(btnLightClickListener);

        model.getBalconyStates().observe(this, balconyStatesObserver);

        return view;
    }

    //上升按钮监听
    View.OnClickListener btnUpClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean[] states = model.getBalconyStates().getValue();
            //在线命令
            myOneNetApi.sendCommand(0, 0, "balcony:1", response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[0] = true;
                    model.setBalconyStates(states);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    //下降按钮监听
    View.OnClickListener btnDownClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean[] states = model.getBalconyStates().getValue();
            //在线命令
            myOneNetApi.sendCommand(0, 0, "balcony1:1", response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[0] = false;
                    model.setBalconyStates(states);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    //照明按钮监听
    View.OnClickListener btnLightClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean[] states = model.getBalconyStates().getValue();
            String command;
            //当前状态为开，则关灯，否则开灯
            if (((MaterialButton)v).getText().charAt(4) == '开') {
                command = "LED41:1";
            }
            else {
                command = "LED41:0";
            }

            //在线命令
            myOneNetApi.sendCommand(0, 0, command, response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[1] = !states[1];
                    model.setBalconyStates(states);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };

    Observer<boolean[]> balconyStatesObserver = new Observer<boolean[]>() {
        @Override
        public void onChanged(boolean[] booleans) {
            Log.d(TAG, "ViewModel中阳台状态改变，阳台：" + booleans[0] + "，照明：" + booleans[1]);
            if (booleans[0]) {
                tv_state.setText(R.string.balcony_state_on);
            }
            else {
                tv_state.setText(R.string.balcony_state_off);
            }
            if (booleans[1]) {
                btn_light.setText(R.string.balcony_light_on);
                btn_light.setIconTintResource(R.color.colorPrimary);
                btn_light.setTextColor(getResources().getColor(R.color.colorPrimary));
            }
            else {
                btn_light.setText(R.string.balcony_light_off);
                btn_light.setIconTintResource(R.color.darker_gray);
                btn_light.setTextColor(getResources().getColor(R.color.darker_gray));
            }
        }
    };
}